package com.cfk.bookmarkdirectory.config;

import com.cfk.bookmarkdirectory.model.BookmarkNode;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * author 3156056300@qq.com
 */
@State(
    name = "BookmarkDirectoryState",
    storages = {
            @Storage("SuperBookmarkDirectoryState.xml")
    }
)
public class BookmarkDirectoryState implements PersistentStateComponent<BookmarkDirectoryState.State> {
    private State myState = new State();

    public static class State {
        public List<BookmarkNodeState> bookmarks = new ArrayList<>();
    }

    public static class BookmarkNodeState {
        public String name;
        public String directoryPath;
        public boolean isDirectory;
        public List<BookmarkNodeState> children = new ArrayList<>();

        public BookmarkNodeState() {}

        public BookmarkNodeState(String name, String directoryPath, boolean isDirectory) {
            this.name = name;
            this.directoryPath = directoryPath;
            this.isDirectory = isDirectory;
        }
    }

    public static BookmarkDirectoryState getInstance(Project project) {
        return project.getService(BookmarkDirectoryState.class);
    }

    @Override
    public @Nullable State getState() {
        return myState;
    }

    @Override
    public void loadState(@NotNull State state) {
        myState = state;
    }

    public void saveBookmarks(List<BookmarkDirectoryState.BookmarkNodeState> bookmarks) {
        myState.bookmarks = new ArrayList<>(bookmarks);
    }

    private BookmarkNodeState convertToState(BookmarkNode node) {
        BookmarkNodeState state = new BookmarkNodeState(
            node.getName(),
            node.getDirectoryPath(),
            node.isDirectory()
        );

        for (int i = 0; i < node.getChildCount(); i++) {
            if (node.getChildAt(i) instanceof BookmarkNode) {
                state.children.add(convertToState((BookmarkNode) node.getChildAt(i)));
            }
        }

        return state;
    }

    public List<BookmarkNodeState> loadBookmarks() {
        return myState.bookmarks;
    }
}